package cn.monkey.family.server.domain.uc.org;

import cn.monkey.family.data.crud.repository.QueryRequestRepository;
import cn.monkey.family.data.uc.org.OrgQueryRequest;
import cn.monkey.family.data.uc.org.Organization;
import com.google.common.base.Strings;
import org.springframework.data.domain.*;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.query.ListQueryByExampleExecutor;

import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface OrgRepository extends ListQueryByExampleExecutor<Organization>, QueryRequestRepository<Organization, String, OrgQueryRequest> {

    default Example<Organization> example(OrgQueryRequest queryRequest) {
        String name = queryRequest.getName();
        Organization organization = new Organization();
        if (Strings.isNullOrEmpty(name)) {
            return Example.of(organization);
        }
        organization.setName(name);
        return Example.of(organization, ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()));
    }


    @Override
    default Page<Organization> findPageByQueryRequest(OrgQueryRequest queryRequest, Pageable pageable) {
        return this.findAll(this.example(queryRequest), pageable);
    }

    @Override
    default List<Organization> findAllByQueryRequest(OrgQueryRequest queryRequest, Sort sort) {
        return this.findAll(this.example(queryRequest), sort);
    }

    @Override
    default Optional<Organization> findOneByQueryRequest(OrgQueryRequest queryRequest) {
        return this.findOne(this.example(queryRequest));
    }
}
